<script>
/*
 * @Author: Your name
 * @Date:   2020-08-12 10:05:31
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-08-13 23:46:41
 */
</script>
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-alert
            title="注意：只允许为第三级分类设置相关参数！"
            type="warning"
            show-icon
          >
          </el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            expand-trigger="hover"
            :options="parentCateList"
            v-model="selectedKeys"
            :props="parentCateProp"
            @change="cascaderHandleChange"
          >
          </el-cascader>
          <!-- tab 页签区域 -->
          <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
            <!-- 静态属性部分 -->
            <el-tab-pane label="静态属性" name="only">
              <!-- 添加属性按钮 -->
              <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog"
                >添加静态属性</el-button
              >
              <!-- 静态属性表格 -->
              <el-table :data="onlyTableData" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="tagHandleClose(index, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 动态编辑标签 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="attr_name" label="属性名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showEditCateDialog(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteCate(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 动态参数部分 -->
            <el-tab-pane label="动态参数" name="many">
              <!-- 添加属性按钮 -->
              <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog"
                >添加动态参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyTableData" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      >{{ item }}</el-tag
                    >
                    <!-- 动态编辑标签 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="attr_name" label="属性名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template>
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="showEditCateDialog(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteCate(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加属性参数的弹出框  静态动态属性公用一个 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addParamsDialogVisible">
      <el-form :model="addParamsForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item :label="titleText + '名称'" prop="attr_name" label-width="120px">
          <el-input v-model="addParamsForm.attr_name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddParams"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改属性参数的弹出框  静态动态属性公用一个 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamsDialogVisible">
      <el-form :model="editParamsForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item :label="titleText + '名称'" prop="attr_name" label-width="120px">
          <el-input v-model="editParamsForm.attr_name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditParams"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { request } from 'network/request.js'
export default {
  name: 'Params',
  data() {
    return {
      // 级联选择器的分类数据
      parentCateList: [],
      // 级联选择器选中的分类id数组
      selectedKeys: [],
      // 级联选择器的配置对象
      parentCateProp: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tab页签当前的点击
      activeName: 'only',
      // 静态属性表格数据
      onlyTableData: [],
      // 动态参数表格数据
      manyTableData: [],
      // 控制添加属性对话框的显示
      addParamsDialogVisible: false,
      // 添加属性表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加表单的校验
      addFormRules: {
        attr_name: [
          { required: true, message: '请填写参数名称', trigger: 'blur' }
        ]
      },
      // 控制编辑属性对话框的显示
      editParamsDialogVisible: false,
      // 编辑属性表单数据
      editParamsForm: {
        attr_name: ''
      },
      // 编辑表单的校验
      editFormRules: {
        attr_name: [
          { required: true, message: '请填写参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取级联框中分类数据
    async getParentCateList() {
      let res = await request({
        url: '/categories',
        method: 'get'
      })
      if (res.meta.status !== 200) {
        this.$message.error('商品分类数据获取失败')
        return
      }
      this.parentCateList = res.data
    },
    // 级联选择器改变的监听
    cascaderHandleChange() {
      // console.log(this.selectedKeys)
      this.getParamsList()
    },
    // tab页签切换触发事件
    tabsHandleClick() {
      this.getParamsList()
    },
    // 获取商品参数（静态或者动态）
    async getParamsList() {
      // 判断选中的是不是三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.onlyTableData = []
        this.manyTableData = []
        return this.$message.error('只能选中三级分类')
      }
      // 是三级分类
      let res = await request({
        url: `/categories/${this.cateId}/attributes`,
        method: 'get',
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取属性列表失败')
        return
      }
      res.data.forEach(item => {
        // 将attr_vals的值转化为数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制动态编辑标签的显示和隐藏
        item.inputVisible = false
        // 动态编辑标签的文本框中的值
        item.inputValue = ''
      })
      // 给对应的table数据赋值
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    // 显示编辑页面
    async showEditCateDialog(info) {
      this.editParamsDialogVisible = true
      // 根据id查询出当前选中的需要编辑的属性
      let res = await request({
        url: `/categories/${this.cateId}/attributes/${info.attr_id}`,
        method: 'get'
      })
      if(res.meta.status !== 200) {
        this.$message.error('获取当前行数据失败')
        return
      }
      this.editParamsForm.attr_name = res.data.attr_name
      this.editParamsForm.attr_id = res.data.attr_id
    },
    // 确认提交编辑的属性
    doEditParams() {
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return
        let res = await request({
          url: `/categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          method: 'put',
          data: {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        })
        if(res.meta.status !== 200) {
          this.$message.error('参数更新失败')
          return
        }
        this.$message.success('参数更新成功')
        this.$refs.editFormRef.resetFields()
        this.editParamsDialogVisible = false
        this.getParamsList()
      })
    },
    // 按钮删除参数
    async deleteCate(info) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      let res = await request({
        url: `categories/${this.cateId}/attributes/${info.attr_id}`,
        method: 'delete'
      })
      if(res.meta.status !== 200) {
        this.$message.error('删除属性失败')
        return
      }
      this.$message.success("删除成功")
      this.getParamsList()
    },
    // 动态编辑标签提交文本框内容
    handleInputConfirm(info) {
      console.log('提交了')
      if (info.inputValue.trim().length === 0) {
        info.inputVisible = false
        info.inputValue = ''
        return
      }
      info.attr_vals.push(info.inputValue.trim())
      info.inputVisible = false
      info.inputValue = ''
      this.saveAttrVals(info)
    },
    // 将对 attr_vals 的操作，保存到数据库
    async saveAttrVals(info) {
      let res = await request({
        url: `/categories/${this.cateId}/attributes/${info.attr_id}`,
        method: 'put',
        data: {
          attr_name: info.attr_name,
          attr_sel: info.attr_sel,
          attr_vals: info.attr_vals.join(' ')
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('编辑动态参数或静态属性失败')
        return
      }
      this.$message.success('编辑参数项成功！')
    },
    // 点击动态文本标签
    showInput(info) {
      info.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 关闭tag标签
    async tagHandleClose(index, info) {
      // 现在页面上删除
      info.attr_vals.splice(index, 1)
      // 然后在数据库中删除参数
      this.saveAttrVals(info)
    },
    // 显示添加属性的弹出框
    showAddParamsDialog() {
      this.addParamsDialogVisible = true
    },
    // 确认提交添加的属性
    doAddParams() {
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) {
          return
        }
        let res = await request({
          url: `categories/${this.cateId}/attributes`,
          method: 'post',
          data: {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        })
        if(res.meta.status != 201) {
          this.$message.error('添加属性失败')
          return
        }
        this.$message.success('添加属性成功')
        this.getParamsList()
        this.addParamsDialogVisible = false
        this.$refs.addFormRef.resetFields()
      })
    }
  },
  created() {
    this.getParentCateList()
  },
  computed: {
    // 添加按钮是否被禁用
    isBtnDisabled() {
      if(this.selectedKeys.length === 0) {
        return true
      }else{
        return false
      }
    },
    // 分类id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 添加属性框标题的动态显示
    titleText() {
      if(this.activeName === 'only') {
        return '静态属性'
      }else{
        return '动态参数'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-alert {
  margin-bottom: 20px;
}
.el-cascader {
  width: 300px;
}
.el-tag {
  margin: 0 5px;
}
.input-new-tag {
  width: 100px;
}
.button-new-tag {
  margin-left: 5px;
}
.el-table {
  margin-top: 20px;
}
</style>
